package com.xjiye_test.payServer.servletGroup.ali;

import com.xjiye_test.payServer.serverletInit.Config;
import com.xjiye_test.payServer.serverletUtil.*;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/22.
 */
public class AliGateway extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, String[]> params = req.getParameterMap();
        String result=null;
        switch (params.get("method")[0]){
            case   "alipay.trade.precreate":
                result=createScanResult(params.get("biz_content")[0]);
                ;
        }
        StringBuffer str=new StringBuffer();
        out.print(result);
        out.flush();
        //PaySignature.rsaSign(encrypt,cus_private_key,"UTF-8");
    }

    protected String createScanResult(String biz_content){
        String payNo= JsonUtil.toJSONObject(biz_content).getString("out_trade_no");
        Map<String,String> map=new HashMap<>();
        map.put("code","10000");
        map.put("msg","Success");
        map.put("out_trade_no",payNo);
        map.put("qr_code","https://ali.aaaa.com");
        String content="{" +
                "    \"alipay_trade_precreate_response\": {" +
                "        \"code\": \"10000\"," +
                "        \"msg\": \"Success\"," +
                "        \"out_trade_no\": \""+payNo+"\"," +
                "        \"qr_code\": \"https://ali.aaaa.com\"" +
                "    }" +
                "}";

        JSONObject json=JsonUtil.toJSONObject(content);
        try {
            //json.put("alipay_trade_precreate_response",map)
            json.put("sign",PaySignature.rsaSign(JsonUtil.toJSONObject(map).toString(),Config.getConfig().getAli_private_key(),"UTF-8"));
        } catch (PlatformPayException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

}
